package com.haiyou.mini.programs.v3;

import com.haiyou.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * v3版本工具类
 */
@Slf4j
public class V3Util {

    public static byte[] signRSA(String data, String priKey) throws Exception {
        //签名的类型
        Signature sign = Signature.getInstance("SHA256withRSA");
        //读取商户私钥,该方法传入商户私钥证书的内容即可
        byte[] keyBytes = Base64.decodeBase64(priKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        sign.initSign(privateKey);
        sign.update(data.getBytes("UTF-8"));
        return sign.sign();
    }

    public static byte[] InputStream2Byte(InputStream in) throws IOException {
        int BUFFER_SIZE = 4096;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count;

        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
            outStream.write(data, 0, count);
        }

        byte[] outByte = outStream.toByteArray();
        outStream.close();
        return outByte;
    }


    /**
     * 获取私钥内容
     *
     * @param filePath
     * @param isDelete
     * @return
     */
    public static String privateKey(String filePath, boolean isDelete) {
        if (com.haiyou.common.util.StringUtils.isEmpty(filePath)) {
            throw new BusinessException("没有配置商户私钥");
        }
        String string;
        try {
            string = FileUtils.readFileToString(new File(filePath));
            if (isDelete) {
                return string.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").trim();
            }
            return string;
        } catch (IOException e) {
            log.error("获取私钥错误！！！{},{}", e.getMessage(), e);
        }
        throw new BusinessException("获取私钥错误");
    }

    /**
     * 获取公钥内容
     *
     * @param filePath
     * @param isDelete
     * @return
     */
    public static String publicKey(String filePath, boolean isDelete) {
        String string;
        try {
            string = FileUtils.readFileToString(new File(filePath));
            if (isDelete) {
                return string.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").trim();
            }
            return string;
        } catch (IOException e) {
            log.error("获取公钥错误！！！{},{}", e.getMessage(), e);
        }
        throw new BusinessException("获取公钥错误");
    }
}
